﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.IO;
using Ymatou.CommonService;
using Ymatou.File.Lib;
using FileHelper = Ymatou.File.Lib.FileHelper;

namespace YmatouFile
{
    /// <summary>
    /// Summary description for BHUploadFile
    /// </summary>
    public class BHUploadFile : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.QueryString["fname"] != null && context.Request.QueryString["type"] != null && context.Request.QueryString["bhkey"] != null)
            {
                //获取上传文件名称
                string fileName = context.Request.QueryString["fname"].ToString();
                //上传文件类型
                string fileType = context.Request.QueryString["type"].ToString().ToLower();
                //key
                string key = context.Request.QueryString["bhkey"].ToString();
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
                string validateKey = FileHelper.ValidateKey;

                //获取图片类型
                string filesource = "";

                if (context.Request.QueryString["source"] != null)
                {
                    filesource = context.Request.QueryString["source"];
                    fileType = FileTool.GetPhysicalFolder(fileType, filesource);
                }

                //是否需要自动生成保存的文件名
                bool generateName = true;
                if(context.Request.QueryString["autoName"] != null)
                {
                    bool.TryParse(context.Request.QueryString["autoName"], out generateName);
                }

                //验证来源的key
                if (key == validateKey)
                {
                    try
                    {
                        string basePath = FileHelper.PhysicalBasePath;

                        //根据文件类型确定存储路径
                        if (string.IsNullOrEmpty(fileType))
                        {
                            fileType = "others";
                        }

                        //保存的文件名
                        string fileSaveName = fileName.Trim();

                        if (generateName)
                        {
                            //自动生成文件名
                            fileSaveName = FileTool.GenerateFileName(fileName);
                        }

                        //保存的路径
                        string savePath = Path.Combine(basePath, fileType);

                        FileTool.SaveFile(context.Request.InputStream, Path.Combine(savePath, fileSaveName));

                        //获取文件存储的相对路径
                        string fileMapPath = Path.Combine(fileType, fileSaveName).Replace("\\","/");

                        //返回文件生成路径
                        context.Response.Write(FileTool.GenerateAccessUrl(fileMapPath));

                    }
                    catch (Exception ex)
                    {
                        ApplicationLog.Error("保存文件出错", ex);
                        context.Response.Write("Error:保存文件出错");
                    }
                }
                else
                {
                    context.Response.Write("Error:参数不匹配");
                }
            }
            else
            {
                context.Response.Write("Error:参数错误");
            }
        }

        /// <summary>
        /// 可以按照不同类型生成不同的重命名规则
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="fileType">暂时没有使用</param>
        /// <returns>新命名的文件</returns>
        private string GenerateFileName(string fileName, string fileType)
        {
            string ext = Path.GetExtension(fileName);

            //使用GUID作为文件名
            string guid = Guid.NewGuid().ToString();

            return guid + ext;
        }

        private void SaveFile(HttpContext context, string fileFullPath)
        {
            if(File.Exists(fileFullPath))
            {
                throw new Exception("已存在相同的文件名");
            }


            string directory = Path.GetDirectoryName(fileFullPath);

            if(!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            //获得上传文件流
            using (Stream uploadStream = context.Request.InputStream)
            {
                //保存上传的文件
                using (FileStream inputStream = File.Create(fileFullPath))
                {
                    try
                    {
                        int bufSize = 1024;
                        int byteGet = 0;
                        byte[] buf = new byte[bufSize];
                        while ((byteGet = uploadStream.Read(buf, 0, bufSize)) > 0)
                        {
                            inputStream.Write(buf, 0, byteGet);
                            inputStream.Flush();
                        }
                    }
                    catch (Exception ex)
                    {
                        throw;
                    }
                }

                uploadStream.Close();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}